package com.admin.system.modules.mnt.rest;

import com.admin.common.utils.FileUtil;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.system.modules.mnt.dto.DeployQueryDTO;
import com.admin.system.modules.mnt.entity.Deploy;
import com.admin.system.modules.mnt.entity.DeployHistory;
import com.admin.system.modules.mnt.service.DeployService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@RestController
@Api(tags = "运维：部署管理")
@RequiredArgsConstructor
@RequestMapping("/api/deploy")
public class DeployController {

    private final String fileSavePath = FileUtil.getTmpDirPath() + "/";
    private final DeployService deployService;

    @ApiOperation(value = "查询")
    @GetMapping
    @PreAuthorize("@ss.check('deploy:list')")
    public ResponseEntity<PageResult<Deploy>> paging(DeployQueryDTO dto) {
        return new ResponseEntity<>(deployService.paging(dto), HttpStatus.OK);
    }

    @Log(module = "部署管理", operateType = OperateTypeEnum.ADD)
    @ApiOperation(value = "新增部署")
    @PostMapping
    @PreAuthorize("@ss.check('deploy:add')")
    public ResponseEntity<Object> add(@Validated @RequestBody Deploy entity) {
        deployService.add(entity);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log(module = "部署管理", operateType = OperateTypeEnum.MODIFY)
    @ApiOperation(value = "修改部署")
    @PutMapping
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<Object> modify(@Validated @RequestBody Deploy entity) {
        deployService.modify(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "部署管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation(value = "删除部署")
    @DeleteMapping
    @PreAuthorize("@ss.check('deploy:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<Integer> ids) {
        deployService.remove(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log(module = "部署管理", operateType = OperateTypeEnum.UPLOAD_FILE)
    @ApiOperation(value = "上传文件部署")
    @PostMapping(value = "/upload")
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<Object> upload(@RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String fileName = "";
        if (file != null) {
            fileName = file.getOriginalFilename();
            File deployFile = new File(fileSavePath + fileName);
            FileUtil.del(deployFile);
            file.transferTo(deployFile);
            //文件下一步要根据文件名字来
            deployService.deploy(fileSavePath + fileName, id);
        } else {
            System.out.println("没有找到相对应的文件");
        }
        System.out.println("文件上传的原名称为:" + Objects.requireNonNull(file).getOriginalFilename());
        Map<String, Object> map = new HashMap<>(2);
        map.put("errno", 0);
        map.put("id", fileName);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @Log(module = "部署管理-系统还原")
    @ApiOperation(value = "系统还原")
    @PostMapping(value = "/serverReduction")
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<String> reduction(@Validated @RequestBody DeployHistory entity) {
        String result = deployService.reduction(entity);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Log(module = "部署管理-服务运行状态")
    @ApiOperation(value = "服务运行状态")
    @PostMapping(value = "/serverStatus")
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<String> serverStatus(@Validated @RequestBody Deploy entity) {
        String result = deployService.serverStatus(entity);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Log(module = "部署管理-启动服务")
    @ApiOperation(value = "启动服务")
    @PostMapping(value = "/startServer")
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<String> startServer(@Validated @RequestBody Deploy entity) {
        String result = deployService.start(entity);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Log(module = "部署管理-停止服务")
    @ApiOperation(value = "停止服务")
    @PostMapping(value = "/stopServer")
    @PreAuthorize("@ss.check('deploy:edit')")
    public ResponseEntity<String> stopServer(@Validated @RequestBody Deploy entity) {
        String result = deployService.stop(entity);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Log(module = "部署管理", operateType = OperateTypeEnum.EXPORT)
    @ApiOperation("导出")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('database:list')")
    public void export(HttpServletResponse response, DeployQueryDTO dto) throws IOException {
        List<Deploy> deploys = deployService.list(dto);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Deploy deploy : deploys) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("应用名称", deploy.getApp().getName());
            map.put("服务器", deploy.getServers());
            map.put("部署日期", deploy.getCreateTime());
            list.add(map);
        }
        MultipartFileUtil.downloadExcel(list, response);
    }
}
